import {useLoad} from "@tarojs/taro";
import {View} from "@tarojs/components";
import React, {useState} from "react";
import Calendar from '@taroify/core/calendar'
import Cell from '@taroify/core/cell'
import Field from '@taroify/core/field'
import Input from '@taroify/core/input'
import PickerField from "@/pages/order/PickerField";
import http from "@/request";
import Button from "@taroify/core/button";
import {HideLoading, ShowLoading, ShowToast, ToPage} from "@/utils";
import dayjs from "dayjs";
import '@taroify/core/calendar/style'

const OrderChange: React.FC = () => {

    const [formData, setFormData] = useState<{
        ids?: string[],
        [key: string]: any
    }>({
        orderComment: '',
        appointmentProcessingDate: '',
        teamId: '',
        userCode: '',
        id: undefined,
        ids: undefined,
        title: '',
        dispatchType: '2'
    });
    const [persons, setPersons] = useState<{ label: string, value: string }[]>([]);
    const [teams, setTeams] = useState<{ label: string, value: string }[]>([]);
    const setFormValue = (key: string, val: any) => {
        setFormData(data => {
            return {
                ...data,
                [key]: val
            }
        })
    }
    const getTeams = () => {
        http.post('/disp/biz/team/page', {
            pageNum: 1,
            pageSize: 9999,
            status: 'Enable',
            teamType: 'Biz'
        }).then(res => {
            const options = (res.data.list || []).map((item: {teamName: string, id: string}) => {
                return {
                    value: item.id,
                    label: item.teamName
                }
            })
            setTeams(options)
        })
    }
    const getPersonList = (teamId: any) => {
        http.post('/disp/sys/user/page', {
            pageNum: 1,
            pageSize: 9999,
            teamId,
            status: 'Enable'
        }).then(res => {
            setPersons((res.data.list || []).map((item: {
                userCode: string,
                username: string,
            }) => {
                return {
                    value: item.userCode,
                    label: item.username
                }
            }))
        })
    }
    const [type, setType] = useState("")
    useLoad((params) => {
        setType(params.type);
        const {id, ids} = params
        if (ids) {
            const idArray = ids.split(',')
            if (idArray.length > 1) {
                setFormValue('ids', idArray)
                setFormValue('dispatchType', '1')
            } else {
                setFormValue('id', ids)
            }
        }
        if (id) {
            setFormValue('id', id)
        }
        getPersonList(params.teamId)
        getTeams()
    })
    const requestFunc = () => {
        if (type === 'dispatch') {
            if (formData.dispatchType === '1') {
                const { id, ids } = formData
                const url = ids ? `/disp/biz/order/batchAssignBizTeamUser` : '/disp/biz/order/assignTeamUser'
                return http.post(url, {
                    id,
                    orderIds: ids,
                    userCode: formData.userCode,
                    orderComment: formData.orderComment,
                })
            } else {
                return http.post('/disp/biz/order/assignTeam', {
                    id: formData.id,
                    teamId: formData.teamId,
                    orderComment: formData.orderComment,
                })
            }
        } else if (type === 'reschedule') {
            return http.post('/disp/biz/order/rescheduleOrder', {
                id: formData.id,
                orderComment: formData.orderComment,
                appointmentProcessingDate: formData.appointmentProcessingDate,
            })
        } else if (type === 'fail') {
            return http.post('/disp/biz/order/failOrder', {
                id: formData.id,
                orderComment: formData.orderComment,
                appointmentProcessingDate: formData.appointmentProcessingDate,
            })
        }
    }
    const submitData = () => {
        ShowLoading()
        requestFunc()?.then(() => {
            ShowToast('操作成功')
            ToPage('/pages/order/index', true)
        }).catch(err => {
            ShowToast(err.msg || '操作失败！')
        }).finally(() => {
            HideLoading()
        })
    }

    function formatFullDate(date?: Date) {
        const str = dayjs(date).format('YYYY-MM-DD HH:mm:ss')
        setFormValue('appointmentProcessingDate', str)
        return str
    }

    function SingleCalendar() {
        const [open, setOpen] = useState(false)
        const [value, setValue] = useState<Date>()

        return (
            <>
                <Cell title="选择改约日期" isLink children={formData.appointmentProcessingDate && dayjs(formData.appointmentProcessingDate).format('YYYY-MM-DD')}
                      onClick={() => setOpen(true)}/>
                <Calendar
                    type="single"
                    value={value}
                    poppable
                    showPopup={open}
                    onClose={setOpen}
                    onChange={setValue}
                    onConfirm={(newValue) => {
                        setOpen(false)
                        formatFullDate(newValue)
                    }}
                ></Calendar>
            </>
        )
    }


    return (<View className={'page flex-column'}>
        <Cell title="操作类型">{{fail: '订单未成功', reschedule: '订单改约', dispatch: '指派订单'}[type]}</Cell>
        {
            type === 'dispatch' ?
                (<>
                    <PickerField
                        key={'dispatchType'}
                        label={'指派类型'}
                        disabled={formData.ids && formData.ids?.length > 1}
                        options={[{label: '个人', value: '1'}, {label: '团队', value: '2'}]}
                        onChange={(item) => setFormValue('dispatchType', item.value)}
                        value={formData.dispatchType}/>
                    {
                        formData.dispatchType === '2' ?
                            <PickerField
                                key={'teamId'}
                                label={'团队'}
                                options={teams}
                                onChange={(item) => setFormValue('teamId', item.value)}
                                value={formData.teamId}/> :
                            <PickerField
                                key={'userCode'}
                                label={'业务员'}
                                options={persons}
                                onChange={(item) => setFormValue('userCode', item.value)}
                                value={formData.userCode}/>
                    }
                </>) : null
        }
        {
            type === 'reschedule' && <SingleCalendar/>
        }
        <Field label={'备注'}>
            <Input placeholder="请输入" value={formData.orderComment}
                   onChange={(e) => setFormValue('orderComment', e.detail.value)}/>
        </Field>
        <View className="flex1"></View>
        <View style={{margin: "16px"}}>
            <Button shape="round" block color="primary" onClick={submitData}>
                提交
            </Button>
        </View>
    </View>)
}
export default OrderChange;